Ext.Loader.setPath('Ext.ux', './ext402/examples/ux');
Ext.require([
    'Ext.form.Panel'
    //'Ext.ux.form.ItemSelector',
    //'Ext.ux.RowExpander'
]);
Ext.define('NF.view.farm.CheckupDetails', {
    extend:'Ext.grid.Panel',
    alias:'widget.checkupDetails',
    frame:true,
    activatedAtleastOnce:false,
    docsStore:null,
    checkupStore:null,
    diseaseStore:null,
    vaccineTypeStore:null,
    autoScroll:true,
    selType: 'rowmodel',
    initComponent:function(){
        var self=this;
        self.prepareCheckupStore();
        self.prepareDiseaseStore();
        self.prepareVaccineTypeStore();
        this.plugins = [
            Ext.create('Ext.grid.plugin.RowEditing', {
                clicksToEdit: 1
            })
        ],
        this.columns= [
            {header: 'Doctor Name',  dataIndex: 'docName',flex:1},
            {header: 'Expense Amount', dataIndex: 'expenseAmount',flex:1},
            {header: 'Payment Date',dataIndex: 'dateOfPayment',flex:1,
                editor: {xtype:'datefield',format: 'F j, Y',allowBlank:false},
                renderer: function(dateOfLactation){
                    return Ext.util.Format.date(dateOfLactation,'F j, Y')
                }
            },
            {header: 'Date of Checkup', dataIndex: 'dateOfCheckup',flex:1,
                editor: {xtype:'datefield',format: 'F j, Y',allowBlank:false},
                renderer: function(dateOfLactation){
                    return Ext.util.Format.date(dateOfLactation,'F j, Y')
                }
            },
            {header: 'Checkup Type', dataIndex: 'checkupTypeDescription',flex:1}
        ],

        this.store = Ext.create('Ext.data.Store',{
           model:'NF.model.CheckupDetails',
           autoLoad:false,
           pageSize:5,
           autoSync:false,
           proxy:{
               type:'ajax',
               url:'checkup/checkupDetails.json',
               reader:{
                   type:'json',
                   root:'checkupDetails',
                   total:'total'
               }
           },
           listeners:{
               update:self.handleUpdate
           }
        }); //this.store is closed.

        this.dockedItems = [
            {
                xtype: 'pagingtoolbar',
                store: self.store,
                dock: 'top',
                displayInfo: true,
                items:[
                    {
                        xtype:'button',
                        iconCls: 'icon-add',
                        text: 'Add Checkup',
                        listeners:{
                            click:self.addNewRecord,
                            context:self.context,
                            selfer:self
                        }
                    }
                ]
            }
        ],//dockedItems

        this.callParent(arguments);
        this.setTitle("Checkup Details");
        self.activatedAtleastOnce=true;
        self.prepareGrid();
    },
    handleUpdate:function(thisStore, updatedRecord, operation, options){
        Ext.Ajax.request({
            url: 'checkup/updateCheckupDetails.json',
            params: updatedRecord.data,
            success: function(response){
                var text = response.responseText;
                thisStore.load();
            }
        });
    },
    prepareGrid:function(){
        var self=this;
        var checkupStore = self.getStore();
        checkupStore.getProxy().extraParams.id = self.context.id;
        checkupStore.load();
    },
    addNewRecord:function(thisButton,eventObject,contextObject){
        var self = this;
        var checkupDetailsWindow = Ext.create('Ext.window.Window', {
            title: 'Add Checkup Details',
            autoHeight: true,
            width: 800,
            height:600,
            layout: 'fit',
            modal:true,
            listeners:{
                close:function() {
                    contextObject.selfer.prepareGrid();
                }
            }
        });
        checkupDetailsWindow.add(contextObject.selfer.createCheckupDetailsForm());
        checkupDetailsWindow.show();
        checkupDetailsWindow.doComponentLayout();
    },
    createCheckupDetailsForm:function(){
        var self=this;
        var checkupDetailsForm = Ext.create("Ext.form.Panel",{
           url:"checkup/updateCheckupDetails.json",
           frame:true,
           autoScroll:true,
           bodyPadding: 10,
           items: [
               {
                    xtype:'combobox',
                    triggerAction: 'all',
                    selectOnTab: true,
                    fieldLabel:'Doctor Name',
                    displayField:'personName',
                    valueField:'personId',
                    name:'personId',
                    allowBlank:false,
                    lazyRender:true,
                    store:self.prepareDoctorsStore(),
                    queryMode:'local'
               },
               {
                    xtype: 'numberfield',
                    fieldLabel: 'Expense Amount',
                    name: 'expenseAmount',
                    allowBlank:false
                },
               {
                    xtype: 'datefield',
                    fieldLabel: 'Date of Payment',
                    name: 'dateOfPayment',
                    format: "c",
                    allowBlank:false,
                    value:new Date()
                },
                {
                    xtype: 'datefield',
                    fieldLabel: 'Date of Checkup',
                    name: 'dateOfCheckup',
                    format: "c",
                    allowBlank:false,
                    value:new Date()
                },
                {
                    xtype:'combobox',
                    triggerAction: 'all',
                    selectOnTab: true,
                    fieldLabel:'Checkup Type',
                    displayField:'description',
                    valueField:'id',
                    name:'checkupTypeId',
                    allowBlank:false,
                    lazyRender:true,
                    store:self.prepareCheckupStore(),
                    queryMode:'local'
               },
               {
                   xtype: 'itemselector',
                   name: 'vaccineTypes',
                   anchor: '100%',
                   fieldLabel: 'Vaccine Selector',
                   //imagePath: './ext402/examples/ux/css/images/',
                   store: self.prepareVaccineTypeStore(),
                   displayField: 'vaccineTypeDescription',
                   valueField: 'id',
                   allowBlank: true,
                   lazyRender:false,
                   msgTarget: 'side'
               },
               {
                   xtype: 'itemselector',
                   name: 'diseaseTypes',
                   anchor: '100%',
                   fieldLabel: 'MedicalAttention Selector',
                   //imagePath: './ext402/examples/ux/css/images/',
                   store: self.prepareDiseaseStore(),
                   displayField: 'diseaseTypeDescription',
                   valueField: 'id',
                   allowBlank: true,
                   lazyRender:false,
                   msgTarget: 'side'
               },
               {
                    xtype: 'hiddenfield',
                    name: 'livestockId',
                    value:self.context.id,
                    allowBlank:false
                }],
               buttons: [
                {
                    text: 'Submit',
                    handler: function() {
                        var self=this;
                        var form = this.up('form').getForm(); // get the basic form
                        if (form.isValid()) { // make sure the form contains valid data before submitting
                             form.submit({
                                success: function(form, action) {
                                   self.up('window').close();
                                },
                                failure: function(form, action) {
                                    Ext.Msg.alert('Failed', action.result.msg);
                                }
                             });
                        } else { // display error alert if the data is invalid
                            Ext.Msg.alert('Invalid Data', 'Please correct form errors.')
                        }
                    }
                },
               {
                    text:'Reset',
                    handler:function(){
                        var self=this;
                        var form = this.up('form').getForm();
                        form.reset();
                    }
               }
            ] //buttons closed.
        });
        return checkupDetailsForm;
    },
    prepareCheckupStore:function(){
        var self=this;
        if(self.checkupStore == null || self.checkupStore == undefined){
            self.checkupStore = Ext.create('Ext.data.Store',{
               model:'NF.model.CheckupType',
               autoLoad:false,
               proxy:{
                   type:'ajax',
                   url:'checkup/getAllCheckupTypes.json',
                   reader:{
                      type:'json',
                      root:'checkupTypes'
                   }
               }
            });
        }
        self.checkupStore.load();
        return self.checkupStore;
    },
    prepareDoctorsStore:function(){
        var self=this;
        if(self.docsStore == null || self.docsStore == undefined){
            self.docsStore = Ext.create('Ext.data.Store',{
               model:'NF.model.Person',
               autoLoad:false,
               proxy:{
                   type:'ajax',
                   url:'person/findByRoleType.json',
                   extraParams:{'id':self.context.id,'roleTypes':'FARM_DOCTOR'},
                   reader:{
                      type:'json',
                      root:'personsDetails'
                   }
               }
            });
        }
        self.docsStore.load();
        return self.docsStore;
    },
    prepareVaccineTypeStore:function(){
        var self=this;
        if(self.vaccineTypeStore === null || self.vaccineTypeStore === undefined){
            self.vaccineTypeStore = Ext.create('Ext.data.Store',{
               model:'NF.model.VaccineType',
               autoLoad:false,
               proxy:{
                   type:'ajax',
                   url:'checkup/getAllVaccineTypes.json',
                   reader:{
                      type:'json',
                      root:'vaccineTypes'
                   }
               }
            });
            self.vaccineTypeStore.load();
        }
        return self.vaccineTypeStore;
    },
    prepareDiseaseStore:function(){
        var self=this;
        if(self.diseaseStore === null || self.diseaseStore === undefined){
            self.diseaseStore = Ext.create('Ext.data.Store',{
               model:'NF.model.Disease',
               autoLoad:false,
               proxy:{
                   type:'ajax',
                   url:'checkup/getAllDiseaseTypes.json',
                   reader:{
                      type:'json',
                      root:'diseases'
                   }
               }
            });
            self.diseaseStore.load();
        }
        return self.diseaseStore;
    }
});